// Electron窗口界面库--创建和管理应用程序窗口(渲染器进程)
const {
  app,
  BrowserWindow,
  dialog,
  globalShortcut,
  Menu,
  screen,
} = require("electron");

// 命令行解析
const process = require("process");

// 存储计算机具有的所有显示器信息
let screens = [];

/**
 * 根据传入参数，创建窗口
 * @param {*} url 
 * @param {*} screenId 
 */
function createWindow(url, screenId) {
  screens = screen.getAllDisplays();  //存储所有的屏幕信息
  Menu.setApplicationMenu(null);      //隐藏浏览器菜单栏

  //注册打开开发者工具的快捷键
  let ret = globalShortcut.register("Ctrl+Shift+D", () => {
    let currnetWindow = BrowserWindow.getFocusedWindow();
    currnetWindow.webContents.openDevTools();
  });
  if (!ret) {
    console.log("Register Dev Tools Shortcut failed!");
  }

  //注册窗口关闭的快捷键
  ret = globalShortcut.register("Ctrl+Shift+X", () => {
    let currnetWindow = BrowserWindow.getFocusedWindow();
    if (currnetWindow != null)
      //销毁当前窗口后，并不能够直接获得第二块屏幕的焦点，需要判断当前窗口是否是null
      currnetWindow.close();
  });
  if (!ret) {
    console.log("Register Window Close Shortcut failed!");
  }

  //注册程序最大化-正常化的切换快捷键
  ret = globalShortcut.register("Ctrl+Shift+M", () => {
    let currnetWindow = BrowserWindow.getFocusedWindow();
    if (currnetWindow.isMaximized()) currnetWindow.unmaximize();
    else currnetWindow.maximize();
  });
  if (!ret) {
    console.log("Register Size Switch Shortcut failed!");
  }

  //获取屏幕id和相关参数
  if (screenId >= screens.length) screenId = screens.length - 1;
  let { x, y, width, height } = screens[screenId].bounds;

  // Create the browser window.
  win = new BrowserWindow({
    x,
    y,
    width: width,
    height: height,
    title: "jmbrowser",
    frame: false, //去掉顶部导航 去掉关闭按钮 最大化最小化按钮
  });

  // and load the index.html of the app.
  win.loadURL(url);

  //在加载页面时，渲染进程第一次完成绘制时，如果窗口还没有被显示，渲染进程会发出 ready-to-show 事件 。 在此事件后显示窗口将没有视觉闪烁
  win.once("ready-to-show", () => {
    win.show();
  });

  // Emitted when the window is closed.
  win.on("closed", () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null;
  });

  //4.最大化主窗口
  win.maximize();
}

/**
 * 在Electron应用一启动并且准备创建浏览器窗口前调用该方法
 */
app.whenReady().then(() => {
  let argvs = process.argv;
  let url = undefined;
  let screen = 0;
  for (const [idx, element] of argvs.entries()) {
    let str = element.toString();
    if (str.includes("--url")) {
      let index = str.lastIndexOf("=");
      url = str.substring(index + 1, str.length);
    }
    if (str.includes("--screen")) {
      screen = str[str.length - 1];
    }
  }
  createWindow(url, screen);
});

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

/**
 * 程序在即将退出时调用的方法,程序想要退出会销毁所有的窗口
 */
app.on("will-quit", () => {});
